'use strict';
const Controller = require('./base');
class CategoryController extends Controller {
  async list() {
    try {
      const { service } = this;
      const list = await service.category.find();
      if (list.count !== 0) {
        const cloneData = JSON.parse(JSON.stringify(list.rows));
        // const category = cloneData.filter(father => {
        //   const arr = list.rows.filter(child => father.category_id === child.pid);
        //   arr.length > 0 ? father.children = arr : '';
        //   return father.pid === 0;
        // });
        list.rows = cloneData;
      }
      this.success(list);
    } catch (err) {
      this.fail(err);
    }
  }

  async create() {
    try {
      const { ctx, service } = this;
      const result = await service.category.create({ ...ctx.request.body });
      this.success(result);
    } catch (err) {
      this.fail(err);
    }
  }

  async findId() {
    try {
      const { ctx, service } = this;
      const id = ctx.query.id;
      const category = await service.category.findId(id);
      this.success(category);
    } catch (e) {
      this.fail(e);
    }
  }

  async update() {
    const { ctx, service } = this;
    const result = await service.category.update({ ...ctx.request.body });
    this.success(result);
  }

  async delete() {
    const { ctx, service } = this;
    const id = ctx.params.cid;
    const parent = await service.category.findSubId(id);
    if (parent) {
      this.success({
        status: false,
        message: '请先删除子分类',
      });
    } else {
      const result = await service.category.delete(id);
      if (result) {
        this.success({
          status: true,
          message: '删除成功',
        });
      }
    }
  }
}

module.exports = CategoryController;
